package com.lucky.carcodepro.filter;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class RequestLoggingFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(RequestLoggingFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 获取请求信息
        var ip = httpRequest.getRemoteAddr();
        var method = httpRequest.getMethod();
        var uri = httpRequest.getRequestURI();
        var browser = httpRequest.getHeader("User-Agent");
        var referer = httpRequest.getHeader("Referer");
        var contentType = httpRequest.getHeader("Content-Type");
        HttpSession session = httpRequest.getSession(false);
        var params = JSON.toJSONString(httpRequest.getParameterMap());
        long startTime = System.currentTimeMillis();

        // 继续处理请求
        chain.doFilter(request, response);

        // 日志记录
        long duration = System.currentTimeMillis() - startTime;
        int statusCode = httpResponse.getStatus();

        logger.info("请求信息如下：\n" +
                        "*****  - IP地址: {}\n" +
                        ">>>    ^ 请求方式: {}\n" +
                        ">>>    - 请求路径: {}\n" +
                        ">>>    ^ 使用的浏览器: {}\n" +
                        ">>>    - 路由地址: {}\n" +
                        ">>>    ^ Content-Type: {}\n" +
                        ">>>    - 请求参数: {}\n" +
                        ">>>    ^ Session ID: {}\n" +
                        ">>>    - 响应状态码: {}\n" +
                        "*****  ^ 处理时长: {} 毫秒 \n" +
                        "=============== 分割线 ===============",
                ip, method, uri, browser, referer, contentType, params,
                session != null ? session.getId() : "莫得获取到Session", statusCode, duration);

    }
}
